﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

namespace MusicPlow
{
    public class MainFlow
    {
        public static Task<SearchResults> FreetextFlow(string text, int amount)
        {
            var entireFlowTask = GrooveShark.GetResults(text, amount).
                ContinueWith<SearchResults>(t =>
                {
                    List<SearchResult> results = new List<SearchResult>();

                    Parallel.ForEach<GrooveSharkResult>(t.Result.Result, gsResult =>
                    {
                        var youtubeLinkTask = Youtube.GetSongFromText(gsResult.ArtistName, gsResult.SongName);
                        var imageTask = ImageFetcher.GetImage(gsResult.ImageSearchString);

                        Task.WaitAll(youtubeLinkTask, imageTask);

                        results.Add(new SearchResult()
                        {
                            SongName = gsResult.SongName,
                            ArtistName = gsResult.ArtistName,
                            AlbumName = gsResult.AlbumName,
                            AmazonLink = string.Format("http://www.music-plow.com/?ToAmazon={0}", HttpUtility.UrlEncode(string.Format("{0} {1}", gsResult.ArtistName, gsResult.SongName))),
                            GrooveSharkSongId = gsResult.SongId,
                            ImageHref = imageTask.Result.Result,
                            YoutubeLink = youtubeLinkTask.Result.Result,
                            ITunesLink = string.Format("http://www.music-plow.com/?ToITunes={0}", HttpUtility.UrlEncode(string.Format("{0} {1}", gsResult.ArtistName, gsResult.SongName))),
                            ResultStatistics = new SingleResultStatistic(
                                youtubeLinkTask.Result.RunTime,
                                imageTask.Result.RunTime)
                        });
                    });

                    return new SearchResults()
                    {
                        SearchTerm = text,
                        Results = results,
                        Statistics = new RequestStatistics(t.Result.RunTime, results.Select(q => q.ResultStatistics))
                    };
                });
            return entireFlowTask;
        }
    }
}
